import React, {useEffect} from 'react';
import { Modal, Form, Input } from 'antd';
import FirstOrgListComponent from './FirstOrgListComponent';
import { FormInstance } from 'antd/lib/form';
import { TagListItem } from '../data.d';
import { isNull } from 'lodash';

interface CreateFormProps {
  modalVisible: boolean;
  onSubmit: (values: TagListItem) => void;
  onCancel: () => void;
  values: TagListItem;
}

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

const formRef = React.createRef<FormInstance>();


const TagForm: React.FC<CreateFormProps> = (props) => {
  const { modalVisible, onSubmit, onCancel, values } = props;

  const [form] = Form.useForm();

  useEffect(() => {
    if(modalVisible){
      if(values){//编辑
        form.setFieldsValue({
          id: values.id,
          name: values.name,
          topOrgId:values.topOrgId,
        });
      }else{//新建
        form.resetFields();
      }
    }
  },[modalVisible]);

  const handleFinish = (values: { [key: string]: any }) => {
    if (onSubmit) {
      onSubmit(values as TagListItem);
    }
  };

  const handleUpdate = () => {
    if (!form) return;
    form.submit();
  };

  const modalFooter = { okText: '保存', onOk: handleUpdate, onCancel };

  const renderContent = () => {
    return (
      <>
        <Form.Item name="id" style={{ display: 'none' }}></Form.Item>
        <Form.Item
          name="name"
          label="标签名称"
          rules={[{ required: true, max: 16, whitespace: true }]}
        >
          <Input placeholder="请输入标签名称" style={{width:200}}/>
        </Form.Item>
        <Form.Item
          name="topOrgId"
          label="所属机构"
          rules={[{ required: true }]}
        >
          <FirstOrgListComponent
            init={values.id?true:false}
            disabled={values?values.status:false} 
            defaultvalue={values?values.topOrgId:null} 
            selectChange={(value) => 
              form.setFieldsValue({topOrgId:value})
            }>

            </FirstOrgListComponent>
      
        </Form.Item>
      </>
    );
  };

  return (
    <Modal
      destroyOnClose
      width={400}
      title={values.id ? "编辑标签":"新建标签"}
      visible={modalVisible}
      {...modalFooter}
    >
      <Form {...layout} ref={formRef} form={form} onFinish={handleFinish}>
        {renderContent()}
      </Form>
    </Modal>
  );
};

export default TagForm;
